package cn.linstudy.base;
import com.sun.mail.util.MailSSLSocketFactory;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author ljp
 * @Date 2021/12/13 16:41
 * @Description
 */
@Service
@Slf4j
public class SendEmailUtils {

    public String from = "paifangbaozhushou@fangjitong.com";
    // 登录密码
    public String password = "pfb123.P";
    // 协议
    public String protocol = "smtp";
    // 端口
    public String port = "465";
    // 服务器地址
    public String host = "smtp.exmail.qq.com";

    private String theme = "通知";

    //初始化参数
    public Session initProperties() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);
        // 使用smtp身份验证
        properties.put("mail.smtp.auth", "true");
        // 开启安全协议,使用SSL,企业邮箱必需
        MailSSLSocketFactory mailSSLSocketFactory = null;
        try {
            mailSSLSocketFactory = new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        properties.put("mail.smtp.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        properties.put("mail.smtp.socketFactory.port", port);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
//        session.setDebug(true);
        return session;
    }

    public void email(String emailTo, String title, String content, String[] fileNames) {
        try {
            Session session = initProperties();
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from, from));// 发件人,可以设置发件人的别名
            // 收件人,多人接收，emailTo 逗号分隔
            InternetAddress[] internetAddressTo = InternetAddress.parse(emailTo);
            mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
            // 主题
            if (StringUtils.isEmpty(title)) {
                mimeMessage.setSubject(theme);
            } else {
                mimeMessage.setSubject(title);
            }
            // 时间
            mimeMessage.setSentDate(new Date());
            // 容器类 附件
            MimeMultipart mimeMultipart = new MimeMultipart();
            // 可以包装文本,图片,附件
            if (!StringUtils.isEmpty(content)) {
                MimeBodyPart bodyPart = new MimeBodyPart();
                // 设置内容 getEmailHtml是邮箱内容模板
                bodyPart.setContent(content, "text/html; charset=UTF-8");
                mimeMultipart.addBodyPart(bodyPart);
            }
            if (!StringUtils.isEmpty(fileNames) && fileNames.length > 0) {
                for (String fileName : fileNames) {
                    File attachFile = new File(fileName);
                    if (attachFile.exists()) {
                        MimeBodyPart attachPart = new MimeBodyPart();
                        FileDataSource fileDataSource = new FileDataSource(attachFile);
                        attachPart.setDataHandler(new DataHandler(fileDataSource));
                        attachPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
                        mimeMultipart.addBodyPart(attachPart);
                    } else {
                        log.error("邮件附件文件 {} 不存在", fileName);
                        return;
                    }
                }
            }
            mimeMessage.setContent(mimeMultipart);
            mimeMessage.saveChanges();
            Transport.send(mimeMessage);
            log.error("发送邮件成功");

        } catch (UnsupportedEncodingException | MessagingException e) {
            e.printStackTrace();
            log.error("发送邮件失败：" + emailTo + " ----" + e.getMessage());
        }
    }

    public static void main(String[] args) {
        SendEmailUtils sendEmailUtils = new SendEmailUtils();
        sendEmailUtils
            .email("ljp2020vip@163.com", "拍房帮的数据", "拍房帮的数据", new String[]{"D:\\拍房帮测试账号.xlsx"});
    }
}
